package com.example.helloworld;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class RadioButtonActivity extends AppCompatActivity{

    private RadioGroup rdg1,rdg2;
    private RadioButton rbtn1,rbtn2;
    private TextView tv1;
    private Button rdbtn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rb);

        rdg1 = findViewById(R.id.radioGroup1);
        rdg2 =findViewById(R.id.radioGroup2);
        rbtn1 = findViewById(R.id.radiobtn1);
        rbtn2 = findViewById(R.id.radiobtn2);
        tv1 = findViewById(R.id.rbcb_tv1);
        rdbtn1 = findViewById(R.id.rdidbtn1);

        //RadioGroup设置事件监听器
        class RadioGoupListenr implements RadioGroup.OnCheckedChangeListener{

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(group == rdg1){
                    if(checkedId == R.id.radiobtn1)
                        tv1.setText("您的选择：男");
                    else if(checkedId == R.id.radiobtn2)
                        tv1.setText("您的选择：女");
                }
                if(group == rdg2){
                    if(checkedId == R.id.radiobtn3)
                        Toast.makeText(getApplicationContext(), "您的选择：男", Toast.LENGTH_LONG).show();
                    else if(checkedId == R.id.radiobtn4)
                        Toast.makeText(getApplicationContext(), "您的选择：女", Toast.LENGTH_LONG).show();
                }
            }
        }

        RadioGoupListenr listenr1 = new RadioGoupListenr();
        rdg1.setOnCheckedChangeListener(listenr1);
//        rdg2.setOnCheckedChangeListener(listenr1);


        //通过单击其他按钮获取选中单选按钮的值
        rdbtn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < rdg2.getChildCount(); i++) {
                    RadioButton rd = (RadioButton) rdg2.getChildAt(i);
                    if (rd.isChecked()) {
                        Toast.makeText(getApplicationContext(), "您的选择:" + rd.getText(), Toast.LENGTH_LONG).show();
                        break;
                    }
                }

            }
        });
    }
}